﻿using SuperSocket.ClientEngine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SuperSocketClient
{
    public partial class SuperSocketClient : Form
    {
        SuperSocket.ClientEngine.AsyncTcpSession async=new AsyncTcpSession();
        public SuperSocketClient()
        {
            InitializeComponent();
            // 连接断开事件
            richTextBox1.Text = "默认连接：127.0.0.1:1234\r\n默认发送：123\r\n基于事件，详情看源代码";

            // 连接到服务器事件
            async.Connected += client_Connected;
            // 发生错误的处理
            async.Error += client_Error;
            // 收到服务器数据事件
            async.DataReceived += client_DataReceived;
            async.Closed += client_Closed;
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            string message = "123";
            byte[] data = Encoding.Default.GetBytes(message);
            
            async.Send(data,0,data.Length);
        }
        
        private void btn_StartConnect_Click(object sender, EventArgs e)
        {
            string ip = "127.0.0.1";
            int port = 1234;
            async.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
            
        }
        void client_Error(object sender, ErrorEventArgs e)
        {
            Console.WriteLine(e.Exception.Message);
        }

        void client_Connected(object sender, EventArgs e)
        {
            Console.WriteLine("连接成功");
        }

        void client_DataReceived(object sender, DataEventArgs e)
        {
            string msg = Encoding.Default.GetString(e.Data);
            MessageBox.Show(msg.ToString());
            Console.WriteLine(msg);
        }

        void client_Closed(object sender, EventArgs e)
        {
            Console.WriteLine("连接断开");
        }
    }
}
